package ktmall.service.impl;

import com.ktjiaoyu.ktmall.dao.CategoryDao;
import com.ktjiaoyu.ktmall.dao.impl.CategoryDaoImpl;
import com.ktjiaoyu.ktmall.entity.Category;
import com.ktjiaoyu.ktmall.service.CategoryService;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CategoryServiceImpl implements CategoryService {
    CategoryDao categoryDao = new CategoryDaoImpl();

    @Override
    public List<Category> findAll() {

        return categoryDao.findAll();
    }

    @Override
    public List<Category> findTree() {
        List<Category> all = categoryDao.findAll();
        return buildTree(all,0L);
    }
    private List<Category> buildTree(List<Category> all,Long parentId) {
        List<Category> tree = new ArrayList<Category>();
        for (Category category : all) {
            if (category.getParent_id() != null && category.getParent_id().equals(parentId)) {
                List<Category> children = buildTree(all,category.getId());
                category.setChildren(children);
                tree.add(category);
            }
        }
        return tree;
    }
}
